<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="Sentinel 触发限流的实现类为 FlowSlot。我们再来简单思考一下，要实现触发限流，至少需要完成如下几件事情：  收集实时调用信息。 设置触发限流规则 根据限流规则与调用信息来决定是否对请求进行限流等。  如何收集实时调用信息在前面的文章中已详细介绍，请带着上述问题开始本节的探讨。 1、初始 FlowSlot我们先从 FlotSlot 类的注释来简单认识一下流量控制相关的内容。  根据已">
<meta property="og:type" content="article">
<meta property="og:title" content="Sentinel FlowSlot 限流实现原理(文末附流程图与总结)">
<meta property="og:url" content="https://www.codingw.net/posts/d83864c8.html">
<meta property="og:site_name" content="中间件兴趣圈">
<meta property="og:description" content="Sentinel 触发限流的实现类为 FlowSlot。我们再来简单思考一下，要实现触发限流，至少需要完成如下几件事情：  收集实时调用信息。 设置触发限流规则 根据限流规则与调用信息来决定是否对请求进行限流等。  如何收集实时调用信息在前面的文章中已详细介绍，请带着上述问题开始本节的探讨。 1、初始 FlowSlot我们先从 FlotSlot 类的注释来简单认识一下流量控制相关的内容。  根据已">
<meta property="og:locale">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20200315193331252.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20200315193402645.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20200315193551464.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20200315193943356.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70">
<meta property="og:image" content="https://img-blog.csdnimg.cn/20200315194109133.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70">
<meta property="article:published_time" content="2020-10-06T14:50:35.000Z">
<meta property="article:modified_time" content="2021-04-26T12:37:59.312Z">
<meta property="article:author" content="中间件兴趣圈">
<meta property="article:tag" content="中间件">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img-blog.csdnimg.cn/20200315193331252.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://www.codingw.net/posts/d83864c8.html"/>





  <title>Sentinel FlowSlot 限流实现原理(文末附流程图与总结) | 中间件兴趣圈</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">中间件兴趣圈</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">微信搜『中间件兴趣圈』，回复『Java』获取200本优质电子书</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://www.codingw.net/posts/d83864c8.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="中间件兴趣圈">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Sentinel FlowSlot 限流实现原理(文末附流程图与总结)</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-10-06T22:50:35+08:00">
                2020-10-06
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/sentinel/" itemprop="url" rel="index">
                    <span itemprop="name">sentinel</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/posts/d83864c8.html" class="leancloud_visitors" data-flag-title="Sentinel FlowSlot 限流实现原理(文末附流程图与总结)">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <div id="vip-container"><p>Sentinel 触发限流的实现类为 FlowSlot。我们再来简单思考一下，要实现触发限流，至少需要完成如下几件事情：</p>
<ul>
<li>收集实时调用信息。</li>
<li>设置触发限流规则</li>
<li>根据限流规则与调用信息来决定是否对请求进行限流等。</li>
</ul>
<p>如何收集实时调用信息在前面的文章中已详细介绍，请带着上述问题开始本节的探讨。</p>
<h2 id="1、初始-FlowSlot"><a href="#1、初始-FlowSlot" class="headerlink" title="1、初始 FlowSlot"></a>1、初始 FlowSlot</h2><p>我们先从 FlotSlot 类的注释来简单认识一下流量控制相关的内容。</p>
<ul>
<li>根据已（NodeSelectorSlot、ClusterNodeBuilderSlot 和 StatisticSlot）收集的运行时统计信息，FlowSlot将使用预先设置的规则来决定是否应阻止传入请求。</li>
<li>SphU.entry(resourceName)调用时，如果有任意一条规则被触发则会抛出 FlowException 异常，应用程序可捕捉该异常对业务进行定制化处理。</li>
<li>每一条流控规则(FlowRule)都包含三个要素：流控类别、基于调用链的流控制策略、限流后的处理行为(参考FlowRule相关的注释)。<ul>
<li><pre><code>grade 流量控制的阈值类型
</code></pre>
可选值：QPS(基于QPS限流策略)、并发线程数。</li>
<li>strategy 基于调用链的流控制策略<br>可选值：STRATEGY_DIRECT(根据调用方限流策略)、STRATEGY_RELATE(关联流量限<br>流策略)、STRATEGY_CHAIN(根据调用链入口限流策略)</li>
<li>controlBehavior 流量控制后的采取的行为<br>CONTROL_BEHAVIOR_DEFAULT(直接拒绝)、CONTROL_BEHAVIOR_WARM_UP(预热)、CONTROL_BEHAVIOR_RATE_LIMITER(匀速排队)、<br>CONTROL_BEHAVIOR_WARM_UP_RATE_LIMITER(预热与匀速排队)。</li>
</ul>
</li>
</ul>
<h2 id="2、FlowSlot-详解"><a href="#2、FlowSlot-详解" class="headerlink" title="2、FlowSlot 详解"></a>2、FlowSlot 详解</h2><h4 id="2-1-FlowSlot-类图"><a href="#2-1-FlowSlot-类图" class="headerlink" title="2.1 FlowSlot 类图"></a>2.1 FlowSlot 类图</h4><p><img src="https://img-blog.csdnimg.cn/20200315193331252.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"><br>FlowSlot 的类图非常简单，内部持有一个成员变量，FlowRuleChecker，用来判断是否满足流控触发条件。</p>
<p>在继续探讨 Sentinel 限流之前，我们先来了解一下 FlowRule，即认识一下 Sentienl 流控规则主要包含哪些配置项，为后续的流程做一个消息的准备。</p>
<h4 id="2-2-FlowRule-配置项"><a href="#2-2-FlowRule-配置项" class="headerlink" title="2.2 FlowRule 配置项"></a>2.2 FlowRule 配置项</h4><p>FlowRule 的类体系如图所示：<br><img src="https://img-blog.csdnimg.cn/20200315193402645.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"><br>其属性的含义如下：</p>
<ul>
<li>String resource<br>资源的名称。</li>
<li>String limitApp<br>需要限制的调用来源，对应【新增流控规则界面】的针对来源。</li>
<li>int grade<br>流量控制的阈值类型，目前支持 QPS 与 并发线程数，对应 【新增流控规则界面】的阔值类型。</li>
<li>int strategy<br>基于调用链的流量控制策略，对应【新增流控规则界面】的流控模式，其可选取值在本文开头部分有详细介绍。</li>
<li>String refResource<br>关联资源或入口资源，当流控模式为关联或链路时配置的关联资源或入口资源，对应【新增流控规则界面】的【入口资源】</li>
<li>int controlBehavior<br>流量控制后的采取的行为，其可选取值在本文开头部分有详细介绍，对应【新增流控规则界面】的流控效果。</li>
<li>int warmUpPeriodSec<br>预热时间，如果 controlBehavior 设置为预热(warm up)时，可以配置其预热时间，在【新增流控规则界面】中选择 warm up 类型后，会增加一行，供用户配置，默认值 10s。</li>
<li>int maxQueueingTimeMs<br>最大超时时间，如果 controlBehavior 设置为排队等待时，等待的最大超时时间，默认为500ms。</li>
<li>boolean clusterMode<br>是否是集群限流模式，对应【新增流控规则界面】的是否集群。</li>
<li>ClusterFlowConfig clusterConfig<br>集群扩容相关配置，集群限流将在后续文章中重点介绍。</li>
</ul>
<p>在 sentinel-dashboard 的配置界面如下图所示：<br><img src="https://img-blog.csdnimg.cn/20200315193551464.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"></p>
<span id="more"></span>

<h4 id="2-3-FlowSlot-entry-流程详解"><a href="#2-3-FlowSlot-entry-流程详解" class="headerlink" title="2.3 FlowSlot#entry 流程详解"></a>2.3 FlowSlot#entry 流程详解</h4><p>FlowSlot#entry</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">entry</span><span class="params">(Context context, ResourceWrapper resourceWrapper, DefaultNode node, <span class="keyword">int</span> count,</span></span></span><br><span class="line"><span class="function"><span class="params">                      <span class="keyword">boolean</span> prioritized, Object... args)</span> <span class="keyword">throws</span> Throwable </span>&#123;   <span class="comment">// @1</span></span><br><span class="line">    checkFlow(resourceWrapper, context, node, count, prioritized);       <span class="comment">// @2</span></span><br><span class="line">    fireEntry(context, resourceWrapper, node, count, prioritized, args);  <span class="comment">// @3</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：首先来解释一下该方法的参数：</p>
<ul>
<li>Context context<br>当前 Sentinel 调用的上下文。</li>
<li>ResourceWrapper resourceWrapper<br>当前访问的资源。</li>
<li>DefaultNode node<br>当前上下文环境对应的节点。</li>
<li>int count<br>本次调用需要消耗的“令牌”个数</li>
<li>boolean prioritized<br>是否是高优先级。</li>
<li>Object… args<br>额外参数。</li>
</ul>
<p>代码@2：调用 checkFlow ，根据配置的限流规则，结合实时统计信息，判断是否满足流控条件，如果满足，则触发流控，稍后会详细探讨该方法的实现原理。</p>
<p>代码@3：调用 fireEntry 继续沿着 slot 链进行传播。</p>
<p>FlowSlot 的 checkFlow 方法在内部就是直接调用 FlowRuleChecker 的 checkFlow 方法，故我们将目光放到 FlowRuleChecker 中。</p>
<h4 id="2-4-FlowRuleChecker-checkFlow-方法详解"><a href="#2-4-FlowRuleChecker-checkFlow-方法详解" class="headerlink" title="2.4 FlowRuleChecker checkFlow 方法详解"></a>2.4 FlowRuleChecker checkFlow 方法详解</h4><p>FlowRuleChecker#checkFlow</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">checkFlow</span><span class="params">(Function&lt;String, Collection&lt;FlowRule&gt;&gt; ruleProvider, ResourceWrapper resource,</span></span></span><br><span class="line"><span class="function"><span class="params">                          Context context, DefaultNode node, <span class="keyword">int</span> count, <span class="keyword">boolean</span> prioritized)</span> <span class="keyword">throws</span> BlockException </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (ruleProvider == <span class="keyword">null</span> || resource == <span class="keyword">null</span>) &#123; </span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    Collection&lt;FlowRule&gt; rules = ruleProvider.apply(resource.getName());   <span class="comment">// @1</span></span><br><span class="line">    <span class="keyword">if</span> (rules != <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">for</span> (FlowRule rule : rules) &#123;</span><br><span class="line">            <span class="keyword">if</span> (!canPassCheck(rule, context, node, count, prioritized)) &#123;            <span class="comment">// @2</span></span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> FlowException(rule.getLimitApp(), rule);</span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：通过限流规则提供器获取与该资源相关的流控规则列表。</p>
<p>代码@2：然后遍历流控规则列表，通过调用 canPassCheck 方法来判断是否满足该规则设置的条件，如果满足流控规则，则抛出 FlowException，即只需要满足一个即结束校验。</p>
<p>接下来继续查看 canPassCheck 方法。</p>
<h5 id="2-4-1-FlowRuleChecker-canPassCheck-详解"><a href="#2-4-1-FlowRuleChecker-canPassCheck-详解" class="headerlink" title="2.4.1 FlowRuleChecker canPassCheck 详解"></a>2.4.1 FlowRuleChecker canPassCheck 详解</h5><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">canPassCheck</span><span class="params">(FlowRule rule, Context context, DefaultNode node, </span></span></span><br><span class="line"><span class="function"><span class="params">				<span class="keyword">int</span> acquireCount, <span class="keyword">boolean</span> prioritized)</span> </span>&#123;</span><br><span class="line">    String limitApp = rule.getLimitApp(); </span><br><span class="line">    <span class="keyword">if</span> (limitApp == <span class="keyword">null</span>) &#123;    <span class="comment">// @1</span></span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">if</span> (rule.isClusterMode()) &#123;  <span class="comment">// @2</span></span><br><span class="line">        <span class="keyword">return</span> passClusterCheck(rule, context, node, acquireCount, prioritized);  </span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> passLocalCheck(rule, context, node, acquireCount, prioritized);     </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：如果限流规则没有配置针对来源，则直接默认通过，该值在配置时，默认为 default，即对所有调用发起方都生效。</p>
<p>代码@2：如果是集群限流模式，则调用 passClusterCheck，非集群限流模式则调用 passLocalCheck 方法，本文重点讲述单节点限流，集群限流模式将在后续文章中详细探讨。</p>
<p>FlowRuleChecker#passLocalCheck</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">static</span> <span class="keyword">boolean</span> <span class="title">passLocalCheck</span><span class="params">(FlowRule rule, Context context, DefaultNode node, <span class="keyword">int</span> acquireCount,</span></span></span><br><span class="line"><span class="function"><span class="params">        <span class="keyword">boolean</span> prioritized)</span> </span>&#123;</span><br><span class="line">    Node selectedNode = selectNodeByRequesterAndStrategy(rule, context, node);    <span class="comment">// @1</span></span><br><span class="line">    <span class="keyword">if</span> (selectedNode == <span class="keyword">null</span>) &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> rule.getRater().canPass(selectedNode, acquireCount, prioritized);    <span class="comment">// @2</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：首先根据流控模式(strategy)选择一个合适的 Node，看到这，大家可以思考一下，这一步骤的目的，如果为空，则直接返回 true，表示放行。</p>
<p>代码@2：调用 FlowRule 内部持有的流量控制器来判断是否符合流控规则，最终调用的是 TrafficShapingController canPass 方法。</p>
<p>那我们接下来分别对上述两个方法进行详细展开。</p>
<h6 id="2-4-1-1-selectNodeByRequesterAndStrategy"><a href="#2-4-1-1-selectNodeByRequesterAndStrategy" class="headerlink" title="2.4.1.1 selectNodeByRequesterAndStrategy"></a>2.4.1.1 selectNodeByRequesterAndStrategy</h6><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">FlowRuleChecker#selectNodeByRequesterAndStrategy</span><br><span class="line"><span class="function"><span class="keyword">static</span> Node <span class="title">selectNodeByRequesterAndStrategy</span><span class="params">(FlowRule rule, Context context, DefaultNode node)</span> </span>&#123;</span><br><span class="line">    String limitApp = rule.getLimitApp();</span><br><span class="line">    <span class="keyword">int</span> strategy = rule.getStrategy();</span><br><span class="line">    String origin = context.getOrigin();   <span class="comment">// @1</span></span><br><span class="line">    <span class="keyword">if</span> (limitApp.equals(origin) &amp;&amp; filterOrigin(origin)) &#123;    <span class="comment">// @2</span></span><br><span class="line">        <span class="keyword">if</span> (strategy == RuleConstant.STRATEGY_DIRECT) &#123;</span><br><span class="line">            <span class="comment">// Matches limit origin, return origin statistic node.</span></span><br><span class="line">            <span class="keyword">return</span> context.getOriginNode();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> selectReferenceNode(rule, context, node);</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (RuleConstant.LIMIT_APP_DEFAULT.equals(limitApp)) &#123;  <span class="comment">// @3</span></span><br><span class="line">        <span class="keyword">if</span> (strategy == RuleConstant.STRATEGY_DIRECT) &#123;</span><br><span class="line">            <span class="comment">// Return the cluster node.</span></span><br><span class="line">            <span class="keyword">return</span> node.getClusterNode();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> selectReferenceNode(rule, context, node);</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (RuleConstant.LIMIT_APP_OTHER.equals(limitApp)</span><br><span class="line">            &amp;&amp; FlowRuleManager.isOtherOrigin(origin, rule.getResource())) &#123;    <span class="comment">// @4</span></span><br><span class="line">        <span class="keyword">if</span> (strategy == RuleConstant.STRATEGY_DIRECT) &#123;</span><br><span class="line">            <span class="keyword">return</span> context.getOriginNode();</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> selectReferenceNode(rule, context, node);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在介绍该方法之前，先回答上文提到一个问题，我们知道，要判断是否满足了限流规则所配置的条件，一个重要的点就是要拿到当前的实时统计信息，通过上面介绍限流规则时提到 Sentinel 目前支持3种流控模式（直接、关联、链路），针对模式的不同，选择的实时统计数据的逻辑就应该不同，即该方法主要是根据流控策略找到对应的实时统计信息(Node)。</p>
<p>代码@1：首先先介绍几个局部变量的含义：</p>
<ul>
<li>String limitApp<br>该条限流规则针对的调用方。</li>
<li>int strategy<br>该条限流规则的流控策略。</li>
<li>String origin<br>本次请求的调用方，从当前上下文环境中获取，例如 dubbo 服务提供者，原始调用方为 dubbo 服务提供者的 application。</li>
</ul>
<p>代码@2：如果限流规则配置的针对的调用方与当前请求实际调用来源匹配（并且不是 default、other)时的处理逻辑，其实现的要点：</p>
<ul>
<li>如果流控模式为 RuleConstant.STRATEGY_DIRECT(直接)，则从 context 中获取源调用方所代表的 Node。</li>
<li>如果流控模式为 RuleConstant.STRATEGY_RELATE(关联)，则从集群环境中获取对应关联资源所代表的 Node，通过(ClusterBuilderSlot会收集每一个资源的实时统计信息，子集群限流时详细介绍)</li>
<li>如果流控模式为 RuleConstant.STRATEGY_CHAIN(调用链)，则判断当前调用上下文的入口资源与规则配置的是否一样，如果是，则返回入口资源对应的 Node，否则返回 null，注意：返回空则该条流控规则直接通过。【这部分代码，对应代码中的 selectReferenceNode 方法】</li>
</ul>
<p>代码@3：如果流控规则针对的调用方(limitApp) 配置的为 default，表示对所有的调用源都生效，其获取实时统计节点(Node)的处理逻辑为：</p>
<ul>
<li>如果流控模式为 RuleConstant.STRATEGY_DIRECT，则直接获取本次调用上下文环境对应的节点的ClusterNode。</li>
<li>如果是其他流控模式，与代码@2的获取逻辑一样，都是调用 selectReferenceNode 进行获取。</li>
</ul>
<p>代码@4：如果流控规则针对的调用方为(other)，此时需要判断是否有针对当前的流控规则，只要存在，则这条规则对当前资源“失效”，如果针对该资源没有配置其他额外的流控规则，则获取实时统计节点(Node)的处理逻辑为：</p>
<ul>
<li>如果流控模式为 RuleConstant.STRATEGY_DIRECT(直接)，则从 context 中获取源调用方所代表的 Node。</li>
<li>如果是其他流控模式，与代码@2的获取逻辑一样，都是调用 selectReferenceNode 进行获取。</li>
</ul>
<p>从这里可以看出，流控规则针对调用方如果设置为 other，表示针对没有配置流控规则的资源。</p>
<p>根据流控策略选择合适的 Node 的逻辑就介绍到这里，如果没有选择到合适的 Node，则针对该流控规则，默认放行。</p>
<h6 id="2-4-1-2-TrafficShapingController-canPass"><a href="#2-4-1-2-TrafficShapingController-canPass" class="headerlink" title="2.4.1.2 TrafficShapingController canPass"></a>2.4.1.2 TrafficShapingController canPass</h6><p>经过上一个步骤获取到对应的实时统计数据，接下来就是根据数据与流控规则，是否匹配。Sentinel 中用于实现流控规则的匹配其类体系如图所示：<br><img src="https://img-blog.csdnimg.cn/20200315193943356.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"><br>由于篇幅的关系，本节只会以 DefaultController 来介绍其实现原理，对应【流控模式：快速失败】，由于篇幅的关系，其他两种流控模式将在下文详细探讨。<br>DefaultController#canPass</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">boolean</span> <span class="title">canPass</span><span class="params">(Node node, <span class="keyword">int</span> acquireCount, <span class="keyword">boolean</span> prioritized)</span> </span>&#123;</span><br><span class="line">    <span class="keyword">int</span> curCount = avgUsedTokens(node);     <span class="comment">// @1</span></span><br><span class="line">    <span class="keyword">if</span> (curCount + acquireCount &gt; count) &#123;   <span class="comment">// @2</span></span><br><span class="line">        <span class="keyword">if</span> (prioritized &amp;&amp; grade == RuleConstant.FLOW_GRADE_QPS) &#123;   <span class="comment">// @3</span></span><br><span class="line">            <span class="keyword">long</span> currentTime;</span><br><span class="line">            <span class="keyword">long</span> waitInMs;</span><br><span class="line">            currentTime = TimeUtil.currentTimeMillis();</span><br><span class="line">            waitInMs = node.tryOccupyNext(currentTime, acquireCount, count);   <span class="comment">// @4</span></span><br><span class="line">            <span class="keyword">if</span> (waitInMs &lt; OccupyTimeoutProperty.getOccupyTimeout()) &#123;             <span class="comment">// @5</span></span><br><span class="line">                node.addWaitingRequest(currentTime + waitInMs, acquireCount);</span><br><span class="line">                node.addOccupiedPass(acquireCount);</span><br><span class="line">                sleep(waitInMs);                                                                                  <span class="comment">// @6</span></span><br><span class="line">                <span class="comment">// PriorityWaitException indicates that the request will pass after waiting for &#123;@link @waitInMs&#125;.</span></span><br><span class="line">                <span class="keyword">throw</span> <span class="keyword">new</span> PriorityWaitException(waitInMs);   <span class="comment">// @7</span></span><br><span class="line">            &#125;</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">false</span>;     <span class="comment">// @8</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">true</span>;       <span class="comment">// @9</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：首先先解释一下两个局部变量的含义：</p>
<ul>
<li>int curCount<br>当前已消耗的令牌数量，即当前时间窗口内已创建的线程数量(FLOW_GRADE_THREAD) 或已通过的请求个数(FLOW_GRADE_QPS)。</li>
<li>double count<br>流控规则中配置的阔值(即一个时间窗口中总的令牌个数)</li>
</ul>
<p>代码@2：如果当前请求的令牌数加上已消耗的令牌数之和小于总令牌数，则直接返回true，表示通过，见代码@9;如果当前时间窗口剩余令牌数小于需要申请的令牌数，则需要根据是否有优先级进行不同的处理。</p>
<ul>
<li>如果该请求存在优先级，即 prioritized 设置为 true，并且流控类型为基于QPS进行限流，则进入相关的处理逻辑，见代码@3~@8。</li>
<li>否则直接返回 false，最终会直接抛出 FlowException，即快速失败，应用方可以捕捉该异常，对其业务进行容错处理。</li>
</ul>
<p>代码@4：尝试抢占下一个滑动窗口的令牌，并返回该时间窗口所剩余的时间，如果获取失败，则返回 OccupyTimeoutProperty.getOccupyTimeout() 值，该返回值的作用就是当前申请资源的线程将 sleep(阻塞)的时间。</p>
<p>代码@5：如果 waitInMs 小于抢占的最大超时时间，则在下一个时间窗口中增加对应令牌数，并且线程将sleep，见代码@6。</p>
<p>代码@7：这里不是很明白为什么等待 waitMs 之后，还需要抛出 PriorityWaitException，那这个prioritized 机制、可抢占下一个时间窗口的令牌有什么意义呢？应该是一个BUG吧。</p>
<h2 id="3、总结"><a href="#3、总结" class="headerlink" title="3、总结"></a>3、总结</h2><p>整个 FlowSlot 限流规则就介绍到这里了，为了更加直观的认识其限流的流程，下面给出一张流程图来对上面的源码分析进行一个总结。<br><img src="https://img-blog.csdnimg.cn/20200315194109133.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==,size_16,color_FFFFFF,t_70" alt="在这里插入图片描述"></p>
<p>该篇注重理论与实践相结合，在进行源码解读之前先从流控规则配置界面入手，代入感比较强，文章再提供一张流程图。</p>
<p>整个限流部分目前还有所欠缺的两个部分：<br>1、流程规则的存储与加载。<br>2、其他几种流控后行为(预热、匀速排队等实现原理)</p>
<p>该部分内容将在后续文章中详细介绍，本文疑似发现一个BUG，也请大家一起交流、探讨。<br>在分析 DefaultController canPass 方法时，prioritized 为 true 时，执行 sleep 方法唤醒后不管三七二十一，直接抛出 PriorityWaitException 这是要起到一个什么作用呢？</p>
</div>

			<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
			<script>
			var isMobile = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i);
			if (!isMobile) {
			    var btw = new BTWPlugin();
			    btw.init({
			        "id": "vip-container",
			        "blogId": "18019-1573088808868-542",
			        "name": "中间件兴趣圈",
			        "qrcode": "https://img-blog.csdnimg.cn/20190314214003962.jpg",
			        "keyword": "more"
			    });
			}
			</script>
		
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/posts/56026c9f.html" rel="next" title="RocketMQ事务消息实战">
                <i class="fa fa-chevron-left"></i> RocketMQ事务消息实战
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/posts/fd3813a.html" rel="prev" title="Sentinel Dubbo 适配器看限流与熔断(实战思考篇)">
                Sentinel Dubbo 适配器看限流与熔断(实战思考篇) <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">139</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1%E3%80%81%E5%88%9D%E5%A7%8B-FlowSlot"><span class="nav-number">1.</span> <span class="nav-text">1、初始 FlowSlot</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2%E3%80%81FlowSlot-%E8%AF%A6%E8%A7%A3"><span class="nav-number">2.</span> <span class="nav-text">2、FlowSlot 详解</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#2-1-FlowSlot-%E7%B1%BB%E5%9B%BE"><span class="nav-number">2.0.1.</span> <span class="nav-text">2.1 FlowSlot 类图</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-2-FlowRule-%E9%85%8D%E7%BD%AE%E9%A1%B9"><span class="nav-number">2.0.2.</span> <span class="nav-text">2.2 FlowRule 配置项</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-3-FlowSlot-entry-%E6%B5%81%E7%A8%8B%E8%AF%A6%E8%A7%A3"><span class="nav-number">2.0.3.</span> <span class="nav-text">2.3 FlowSlot#entry 流程详解</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#2-4-FlowRuleChecker-checkFlow-%E6%96%B9%E6%B3%95%E8%AF%A6%E8%A7%A3"><span class="nav-number">2.0.4.</span> <span class="nav-text">2.4 FlowRuleChecker checkFlow 方法详解</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#2-4-1-FlowRuleChecker-canPassCheck-%E8%AF%A6%E8%A7%A3"><span class="nav-number">2.0.4.1.</span> <span class="nav-text">2.4.1 FlowRuleChecker canPassCheck 详解</span></a><ol class="nav-child"><li class="nav-item nav-level-6"><a class="nav-link" href="#2-4-1-1-selectNodeByRequesterAndStrategy"><span class="nav-number">2.0.4.1.1.</span> <span class="nav-text">2.4.1.1 selectNodeByRequesterAndStrategy</span></a></li><li class="nav-item nav-level-6"><a class="nav-link" href="#2-4-1-2-TrafficShapingController-canPass"><span class="nav-number">2.0.4.1.2.</span> <span class="nav-text">2.4.1.2 TrafficShapingController canPass</span></a></li></ol></li></ol></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3%E3%80%81%E6%80%BB%E7%BB%93"><span class="nav-number">3.</span> <span class="nav-text">3、总结</span></a></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">中间件兴趣圈</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("NNEhOL0iOcflg8f1U3HUqiCq-gzGzoHsz", "7kSmkbbb3DktmHALlShDsBUF");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
